package com.iqiyi.pps.epg.api.server.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.pps.epg.api.aop.annotation.SkipAuthCheck;
import com.iqiyi.pps.epg.api.aop.annotation.SkipInterfaceLog;
import com.iqiyi.pps.epg.api.model.web.channel.*;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.server.web.channel.ChannelWebService;
import com.iqiyi.pps.epg.api.server.web.channel.ChannelWebServiceConstants;
import com.iqiyi.pps.epg.api.server.web.program.ProgramWebService;
import com.iqiyi.pps.epg.api.server.web.stream.ChannelStreamWebService;
import com.iqiyi.pps.epg.api.utils.ApiHttpRequestUtil;
import com.iqiyi.pps.epg.api.utils.Constants;
import com.iqiyi.pps.epg.api.utils.RegUtil;
import com.iqiyi.pps.epg.api.utils.ServiceUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.*;

/**
 * Created by karkarrotxu on 2016/9/18.
 */
@Service
public class ChannelProxy extends BaseProxy {
    private static Logger logger = LoggerFactory.getLogger(ChannelProxy.class);

    public String createChannel(String name, String universalCode, String description, String passportId,
                                String ppsBaikeId, String liveType, String carouselTableNo, String type,
                                String logoUrl, String maxPlaybackPeriod,
                                String tempStartTime, String tempEndTime, String qitanId, String orderBy, String isEnable,
                                String tag, String allowPopups, String shouldDisplay,
                                String isQiyiProduced, String exclusiveStatusIqiyi,
                                String interruptHintType, int sliceDelay, String subjectUrl, int automation,
                                int userCount, int cyclical, int formal, String alternatePlayCollection) {
        try {
            if (StringUtils.isBlank(name) || StringUtils.isBlank(liveType) || StringUtils.isBlank(type) || StringUtils.isBlank(logoUrl)
                    || StringUtils.isBlank(maxPlaybackPeriod) || StringUtils.isBlank(isEnable) ) {
                return ServiceUtil.getResponseError("参数不全，请补齐");
            }
            if("3".equals(liveType)  && StringUtils.isBlank(tag)){
                return ServiceUtil.getResponseError("参数不全，请补齐");
            }

            if ("2".equals(liveType) || "3".equals(liveType)) {
                universalCode = UUID.randomUUID().toString();
            }
            if ("3".equals(liveType)  && tag.indexOf("_") <= 0) {
                return Constants.getJsonResponse(Constants.CODE_ERROR_AUTH, null, "分类参数错误");
            }
            if (!liveType.equals("2")) {
                sliceDelay = 0;
                subjectUrl = "";
                formal = 1;
                cyclical = 0;
            }

            TChannel tChannel = new TChannel();
            tChannel.setName(name);
            tChannel.setShortName(name);
            tChannel.setUniversalCode(universalCode);
            tChannel.setDescription(StringUtils.isNotBlank(description) ? description : "");
            long newPassportId = 0l;
            if (StringUtils.isNotBlank(passportId)) {
                try {
                    newPassportId = Long.parseLong(passportId);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("大V帐号不正确");
                }
            }
            long newPpsBaikeId = 0l;
            if (StringUtils.isNotBlank(ppsBaikeId)) {
                try {
                    newPpsBaikeId = Long.parseLong(ppsBaikeId);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("百科id不正确");
                }
            }
            long newQitanId = 0l;
            if (StringUtils.isNotBlank(qitanId)) {
                try {
                    newQitanId = Long.parseLong(qitanId);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("奇谈id不正确");
                }
            }
            int newOrderBy = 0;
            if (StringUtils.isNotBlank(orderBy)) {
                try {
                    newOrderBy = Integer.parseInt(orderBy);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("排序不正确");
                }
            }
            int newMaxPlaybackPeriod = 0;
            if (StringUtils.isNotBlank(maxPlaybackPeriod)) {
                try {
                    newMaxPlaybackPeriod = Integer.parseInt(maxPlaybackPeriod);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("回看时间不正确");
                }
            }
            int newShouldDisplay = 0;
            if (StringUtils.isNotBlank(shouldDisplay)) {
                try {
                    newShouldDisplay = Integer.parseInt(shouldDisplay);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("评论开关不正确");
                }
            }
            int newAllowPopups = 0;
            if (StringUtils.isNotBlank(allowPopups)) {
                try {
                    newAllowPopups = Integer.parseInt(allowPopups);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("弹幕开关不正确");
                }
            }
            int newInterruptHintType = 1;
            if (StringUtils.isNotBlank(interruptHintType)) {
                try {
                    newInterruptHintType = Integer.parseInt(interruptHintType);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("播放器提示信息错误");
                }
            }
            tChannel.setShouldDisplay(newShouldDisplay);
            tChannel.setAllowPopups(newAllowPopups);
            tChannel.setPassportId(newPassportId);
            tChannel.setPpsBaikeId(newPpsBaikeId);
            tChannel.setLiveType(Integer.parseInt(liveType));
            tChannel.setType(Integer.parseInt(type));
            tChannel.setLocation("");
            tChannel.setLogoUrl(logoUrl);
            tChannel.setMaxPlaybackPeriod(newMaxPlaybackPeriod);
            tChannel.setTempName("");
            tChannel.setTempStartTime(tempStartTime);
            tChannel.setTempEndTime(tempEndTime);
            tChannel.setOperator(ServiceUtil.getOpUser());
            tChannel.setQitanId(newQitanId);
            tChannel.setOrderBy(newOrderBy);
            tChannel.setIsEnable(Integer.parseInt(isEnable));
            tChannel.setTag(tag);
            tChannel.setIsMemeberFree(1);
            tChannel.setPaidStartTime("");
            tChannel.setPaidEndTime("");
            tChannel.setIsQiyiProduced(Integer.parseInt(isQiyiProduced));
            tChannel.setExclusiveStatusIqiyi(Integer.parseInt(exclusiveStatusIqiyi));
            tChannel.setInterruptHintType(newInterruptHintType);
            tChannel.setSliceDelay(sliceDelay);
            tChannel.setSubjectUrl(subjectUrl);
            tChannel.setAutomation(automation);
            tChannel.setUserCount(userCount);
            tChannel.setFormal(formal);
            tChannel.setCyclical(cyclical);
            tChannel.setAlternatePlayCollection(alternatePlayCollection);

            int newCarouselTableNo = -1;

            if (StringUtils.isNotBlank(carouselTableNo)) {
                if (RegUtil.isInteger(carouselTableNo)) {
                    try {
                        newCarouselTableNo = Integer.parseInt(carouselTableNo);
                    } catch (NumberFormatException e) {
                        return ServiceUtil.getResponseError("轮播台台号异常:" + carouselTableNo);
                    }
                } else {
                    return ServiceUtil.getResponseError("轮播台台号非整数类型");
                }
            }

            tChannel.setCarouselTableNo(newCarouselTableNo);

            ChannelWebService.Iface service = getChannelService();
            if (!service.checkUnique(0, name, universalCode)) {
                return ServiceUtil.getResponseError("频道名称，节目单代码不能重复");
            }
            Long result = service.create(tChannel);
            if (result > 0) {
                writeChannelLog(result, 100, ServiceUtil.getOpUser(), getStrParam());
                return Constants.getJsonResponse(Constants.CODE_SUC, result, "添加成功");

            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
        } catch (Exception e) {
            logger.error("[ChannelProxy][createChannel]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }

    }

    public String editChannel(String id, String name, String universalCode, String description, String passportId,
                              String ppsBaikeId, String liveType, String carouselTableNo, String type,
                              String logoUrl, String maxPlaybackPeriod,
                              String tempStartTime, String tempEndTime, String qitanId, String orderBy, String isEnable,
                              String tag, String allowPopups, String shouldDisplay,  String isQiyiProduced, String exclusiveStatusIqiyi,
                              String interruptHintType, int sliceDelay, String subjectUrl,
                              int userCount, int cyclical, int formal, String alternatePlayCollection) {
        try {
            if (StringUtils.isBlank(name) || StringUtils.isBlank(liveType) || StringUtils.isBlank(type) || StringUtils.isBlank(logoUrl)
                    || StringUtils.isBlank(maxPlaybackPeriod) || StringUtils.isBlank(isEnable) ) {
                return ServiceUtil.getResponseError("参数不全，请补齐");
            }
            if("3".equals(liveType)  && StringUtils.isBlank(tag)){
                return ServiceUtil.getResponseError("参数不全，请补齐");
            }
            if ("2".equals(liveType) || "3".equals(liveType)) {
                universalCode = UUID.randomUUID().toString();
            }
            if ("3".equals(liveType)  && tag.indexOf("_") <= 0) {
                return Constants.getJsonResponse(Constants.CODE_ERROR_AUTH, null, "分类参数错误");
            }
            if (!liveType.equals("2")) {
                sliceDelay = 0;
                subjectUrl = "";
            }
            Long channelId = Long.parseLong(id);
            if (channelId <= 0) {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }

            ChannelWebService.Iface service = getChannelService();
            TChannel tChannel = service.getById(channelId);
            if (tChannel == null) {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }

            if (!service.checkUnique(channelId, name, universalCode)) {
                return ServiceUtil.getResponseError("频道名称，节目单代码不能重复");
            }
            tChannel.setName(name);
            tChannel.setShortName(name);
            tChannel.setUniversalCode(universalCode);
            tChannel.setDescription(description);
            long newPassportId = 0l;
            if (StringUtils.isNotBlank(passportId)) {
                try {
                    newPassportId = Long.parseLong(passportId);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("大V帐号不正确");
                }
            }
            long newPpsBaikeId = 0l;
            if (StringUtils.isNotBlank(ppsBaikeId)) {
                try {
                    newPpsBaikeId = Long.parseLong(ppsBaikeId);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("百科id不正确");
                }
            }
            long newQitanId = 0l;
            if (StringUtils.isNotBlank(qitanId)) {
                try {
                    newQitanId = Long.parseLong(qitanId);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("奇谈id不正确");
                }
            }
            int newOrderBy = 0;
            if (StringUtils.isNotBlank(orderBy)) {
                try {
                    newOrderBy = Integer.parseInt(orderBy);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("排序不正确");
                }
            }
            int newMaxPlaybackPeriod = 0;
            if (StringUtils.isNotBlank(maxPlaybackPeriod)) {
                try {
                    newMaxPlaybackPeriod = Integer.parseInt(maxPlaybackPeriod);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("回看时间不正确");

                }
            }
            int newInterruptHintType = 0;
            if (StringUtils.isNotBlank(interruptHintType)) {
                try {
                    newInterruptHintType = Integer.parseInt(interruptHintType);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("播放器提示信息错误");
                }
            }
            tChannel.setShouldDisplay(Integer.parseInt(shouldDisplay));
            //     tChannel.setAllowPopups(Integer.parseInt(allowPopups));
            tChannel.setAllowPopups(1);
            tChannel.setPassportId(newPassportId);
            tChannel.setPpsBaikeId(newPpsBaikeId);
            tChannel.setLiveType(Integer.parseInt(liveType));
            tChannel.setType(Integer.parseInt(type));
            tChannel.setLocation("");
            tChannel.setLogoUrl(logoUrl);
            tChannel.setMaxPlaybackPeriod(newMaxPlaybackPeriod);
            tChannel.setTempName("");
            tChannel.setTempStartTime(tempStartTime);
            tChannel.setTempEndTime(tempEndTime);
            tChannel.setOperator(ServiceUtil.getOpUser());
            tChannel.setQitanId(newQitanId);
            tChannel.setOrderBy(newOrderBy);
            tChannel.setIsEnable(Integer.parseInt(isEnable));
            tChannel.setTag(tag);
            tChannel.setIsQiyiProduced(Integer.parseInt(isQiyiProduced));
            tChannel.setExclusiveStatusIqiyi(Integer.parseInt(exclusiveStatusIqiyi));
            tChannel.setInterruptHintType(newInterruptHintType);
            tChannel.setSliceDelay(sliceDelay);
            tChannel.setSubjectUrl(subjectUrl);
            tChannel.setUserCount(userCount);
            tChannel.setCyclical(cyclical);
            tChannel.setFormal(formal);
            tChannel.setAlternatePlayCollection(alternatePlayCollection);

            int newCarouselTableNo = -1;
            if (StringUtils.isNotBlank(carouselTableNo)) {
                try {
                    newCarouselTableNo = Integer.parseInt(carouselTableNo);
                } catch (NumberFormatException e) {
                    return ServiceUtil.getResponseError("轮播台台号非整数类型");

                }
                if (newCarouselTableNo < -1) {
                    return ServiceUtil.getResponseError("无效的轮播台台号:" + newCarouselTableNo);
                }
            } else {
                newCarouselTableNo = ChannelWebServiceConstants.SPECIAL_TABLE_NO; //空数据验证
            }
            tChannel.setCarouselTableNo(newCarouselTableNo);
            if (service.edit(tChannel)) {
                writeChannelLog(channelId, 101, ServiceUtil.getOpUser(), getStrParam());
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "修改成功");

            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }

        } catch (Exception e) {
            logger.error("[editChannel]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    public String getChannel(String id) {
        try {
            ChannelWebService.Iface service = getChannelService();
            TChannel tChannel = service.getById(Long.parseLong(id));
            if (tChannel != null) {
                return Constants.getResponse(Constants.CODE_SUC, tChannel, null).toJsonString();
            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
        } catch (Exception e) {
            logger.error("[getChannel]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    public String hasCarouselTableNo(String carouselTableNo, int type, String channelId) {
        try {
            if (!RegUtil.isInteger(carouselTableNo)) {
                return ServiceUtil.getResponseError("轮播台台号非整数类型");
            }
            ChannelWebService.Iface service = getChannelService();
            boolean ret = service.carouselTableNo(Integer.parseInt(carouselTableNo), type, channelId);
            if (ret) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "轮播台台号已存在");
            } else {
                return ServiceUtil.getResponseError("轮播台台号不存在");
            }
        } catch (Exception e) {
            logger.error("[carouselTableNo]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    @SkipInterfaceLog
    public String getChannelLogList(String channelId, Integer pageNo, Integer pageSize) {
        pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
        pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;
        try {
            ChannelWebService.Iface service = getChannelService();
            Map<String, String> params = new HashMap<>();
            TFilter tFilter = new TFilter();
            params.put("EQL_fatherId", channelId);
            tFilter.setFilters(params);
            TPage page = new TPage(-1, pageNo, pageSize, "id", "desc", true);

            TChannelLogPage tChannelLogPage = service.getChannelLogList(page, tFilter);
            if (tChannelLogPage != null) {
                return Constants.getResponse(Constants.CODE_SUC, tChannelLogPage, "操作成功").toJsonString();
            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
        } catch (Exception e) {
            logger.error("[getChannelLogList]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    @SkipInterfaceLog
    public String getChannelCodeList(String key) {
        try {
            ChannelWebService.Iface service = getChannelService();
            String codeList = service.getChannelCodeList(key);
            return Constants.getJsonResponse(Constants.CODE_SUC, JSON.parse(codeList), null);
        } catch (Exception e) {
            logger.error("[getChannelCodeList]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    @SkipAuthCheck
    public String setPanoFormat(String channelId, String videoType, String angleX, String angleY, String zoomRate) {
        try {
            if (!RegUtil.isPositiveInteger(channelId) || !RegUtil.isPositiveInteger(videoType)) {
                return ServiceUtil.getResponseError("频道Id参数异常");
            }
            if (StringUtils.isNotBlank(angleX) && !RegUtil.isNonnegativeInteger(angleX)) {
                return ServiceUtil.getResponseError("默认视角X轴，请输入非负整数 ");
            }
            if (StringUtils.isNotBlank(angleY) && !RegUtil.isNonnegativeInteger(angleY)) {
                return ServiceUtil.getResponseError("默认视角Y轴，请输入非负整数");
            }
            float checkZoomRate = 1.0f;
            if (StringUtils.isNotBlank(zoomRate)) {
                try {
                    checkZoomRate = Float.parseFloat(zoomRate);
                    if (checkZoomRate <= 0) {
                        return ServiceUtil.getResponseError("默认缩放系数必须大于0");
                    }
                } catch (NumberFormatException formatException) {
                    return ServiceUtil.getResponseError("默认缩放系数设定异常");
                }
            }

            ChannelWebService.Iface service = getChannelService();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("videoType", Integer.valueOf(videoType));
            jsonObject.put("angleX", StringUtils.isBlank(angleX) ? 0 : Integer.valueOf(angleX));
            jsonObject.put("angleY", StringUtils.isBlank(angleY) ? 0 : Integer.valueOf(angleY));
            jsonObject.put("zoomRate", checkZoomRate);
            boolean flag = service.savePanoFormat(Long.valueOf(channelId), jsonObject.toJSONString());
            writeChannelLog(Long.parseLong(channelId), 104, ServiceUtil.getOpUser(), flag ? Constants.CODE_SUC : Constants.CODE_ERROR + "|" + getStrParam());
            if (flag) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "更新成功");
            } else {
                return ServiceUtil.getResponseError("更新频道全景播放失败");
            }
        } catch (Exception e) {
            logger.error("[setPanoFormat][error]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    @SkipAuthCheck
    public String setThreeD(String channelId, String videoType){
        if (!RegUtil.isPositiveInteger(channelId) || !RegUtil.isPositiveInteger(videoType)) {
            return Constants.getJsonResponse(Constants.CODE_ERROR, null, "频道Id参数异常");
        }
        try {
            ChannelWebService.Iface service = getChannelService();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("videoType", Integer.valueOf(videoType));
            boolean flag = service.saveThreeD(Long.valueOf(channelId), jsonObject.toJSONString());
            writeChannelLog(Long.parseLong(channelId), 110, "", flag ? Constants.CODE_SUC : Constants.CODE_ERROR + "|" + getStrParam());
            if (flag) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "更新成功");
            } else {
                return Constants.getJsonResponse(Constants.CODE_ERROR, null, "更新3D直播参数失败");
            }
        } catch (Exception e) {
            logger.error("[setThreeD][error]", e);
            return ServiceUtil.getResponseError("发现异常");
        }
    }

    public String delChannel(final String id) {
        try {
            ChannelStreamWebService.Iface channelStreamWebService = getChannelStreamWebService();
            int iStreamStatus = channelStreamWebService.streamStatus(Long.parseLong(id), null);
            if (iStreamStatus == 1) {
                return ServiceUtil.getResponseError("该频道下还有流在编码，不能删除");
            } else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            getChannelStreamWebService().deleteBy(Long.parseLong(id));
                        } catch (Exception e) {
                            logger.error("[runable][delChannel]", e);
                        }
                    }
                }, "Delete Stream").start();

                ChannelWebService.Iface service = getChannelService();
                boolean ret = service.delChannel(Long.parseLong(id));
                if (ret) {
                    writeChannelLog(Long.parseLong(id), 102, ServiceUtil.getOpUser(), getStrParam());
                    return Constants.getResponse(Constants.CODE_SUC, null, "操作成功").toJsonString();
                } else {
                    return ServiceUtil.getResponseError(PARAMETER_ERROR);
                }
            }
        } catch (Exception e) {
            logger.error("[delChannel]", e);
            return ServiceUtil.getResponseError("删除频道异常");
        }
    }

    @SkipInterfaceLog
    public String channelList(String liveType, String type, String qipuId, String name,
                              String startDate, String endDate, String isEnable, String isDelete,
                              Integer pageNo, Integer pageSize) {
        Map<String, String> params = new HashMap();
        isDelete = null == isDelete ? "0" : isDelete;
        if (!validChannelListParams(liveType, type, qipuId, name,
                startDate, endDate, isEnable, isDelete, params)) {
            return  Constants.getJsonResponse(Constants.CODE_ERROR, null, PARAMETER_ERROR);
        }
        pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
        pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;
        try {
            TChannelPage tChannelPage = new TChannelPage();
            tChannelPage.setTPage(new TPage(-1, pageNo, pageSize, "id", "desc", true));
            TFilter tFilter = new TFilter();
            params.put("pageNo", pageNo + "");
            params.put("pageSize", pageSize + "");
            tFilter.setFilters(params);
            ChannelWebService.Iface service = getChannelService();
            tChannelPage = service.search(tChannelPage.getTPage(), tFilter);
            if (tChannelPage != null) {
                return Constants.getResponse(Constants.CODE_SUC, tChannelPage, null).toJsonString();
            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }

        } catch (Exception e) {
            logger.error("[BasementApiServiceImpl][channelList]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }

    }

    @SkipAuthCheck
    public String channelImage(String entityId, String url, String extend, String code, String message) {
        try {
            boolean ret = false;
            long backId = Long.parseLong(entityId);
            if (code.equals("A00000")) {
                ProgramWebService.Iface pwService = getProgramService();
                switch (extend) {
                    case Constants.EXTEND_NEW_EPG_CHANNEL:
                        ChannelWebService.Iface cwService = getChannelService();
                        ret = cwService.saveLogo(backId, url);
                        logger.info("[saveLog][Channel]" + Boolean.toString(ret));
                        break;
                    case Constants.EXTEND_NEW_EPG_PROGRAM:
                        ret = pwService.saveLogo(backId, url);
                        logger.info("[saveLog][Program]" + Boolean.toString(ret));
                        break;
                    case Constants.EXTEND_NEW_EPG_PROGRAM_SNAPSHOT:
                        ret = pwService.saveSnapPicUrl(backId, url);
                        logger.info("[EPG][API][channelImage][saveSnapShot][Program]" + Boolean.toString(ret));
                        break;
                    default:
                        break;
                }
            }
            switch ( extend ){
                case Constants.EXTEND_NEW_EPG_CHANNEL:
                    writeChannelLog( backId,Constants.LogType.PIC_CALLBACK.getIndex(),null,ret+"|"+ getStrParam() );
                    break;
                case Constants.EXTEND_NEW_EPG_PROGRAM:
                    writeProgramLog( backId,Constants.LogType.PIC_CALLBACK.getIndex(),null,ret+"|"+ getStrParam() );
                    break;
                case Constants.EXTEND_NEW_EPG_PROGRAM_SNAPSHOT:
                    if( !ret ){
                        writeProgramLog( backId,Constants.LogType.MEIZI_SNAPSHOT_WRITE.getIndex(),null,ret+"|"+ getStrParam() );
                    }
                    break;
                default:
                    return Constants.getJsonResponse(Constants.CODE_ERROR, null, "参数错误: extend不能为空");
            }
            if (!ret) {
                return Constants.getJsonResponse(Constants.CODE_ERROR, null, "图片保存失败");
            }
            return Constants.getJsonResponse(Constants.CODE_SUC, null, "操作成功");
        } catch (Exception e) {
            logger.error("[channelImage]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    public String chargeChannel(String qipuId, String purchaseType) {
        return Constants.getJsonResponse(Constants.CODE_FAIL, null, "旧版过时数据");
    }

    public String getPreviewStream(String qipuId) {
        try {
            String url = null;
            String result = null;
            if (DEV_MODE_FLAG) {
                url = "http://qipu-test.qiyi.domain/int/entity/nocache/" + qipuId + ".json";
            } else {
                url = "http://qipu.qiyi.domain/int/entity/nocache/" + qipuId + ".json";
            }
            result = ApiHttpRequestUtil.getMethod(url, null, null);
            Map<String, String> _streamUrl = new HashMap();
            JSONObject jsonStrStream = JSONObject.parseObject(result);
            JSONObject jsonObject = jsonStrStream.getJSONObject("default_live_stream");
            String strFlvUrl = null;
            if (jsonObject != null && jsonObject.containsKey("url")) {
                strFlvUrl = jsonObject.getString("url");
                if (StringUtils.isBlank(strFlvUrl)) {
                    return Constants.getJsonResponse(Constants.CODE_ERROR, null, PARAMETER_ERROR);
                }
            } else if (strFlvUrl == null) {
                return Constants.getJsonResponse(Constants.CODE_ERROR, null, "没有默认码流");
            }

            URL aUrl = new URL(strFlvUrl);
            // String filename = aUrl.getFile();
            String[] filenameArr = aUrl.getFile().split("/");
            String filename = filenameArr[filenameArr.length - 1];
            filenameArr = filename.split("\\.");
            filename = filenameArr[0];
            _streamUrl.put("flv", filename);
            return Constants.getResponse(Constants.CODE_SUC, _streamUrl, null).toJsonString();
        } catch (Exception e) {
            logger.error("[getPreviewStream]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }



    //获取搜索限制
    public String getPlatSettings(String channelId) {
        try {
            if (channelId != null) {
                if (!RegUtil.isPositiveInteger(channelId)) {
                    return ServiceUtil.getResponseError("参数不全");
                }
            } else {
                channelId = "-1";
            }
            ChannelWebService.Iface service = getChannelService();
            TSearchConfig searchConfig = service.searchSearchConfig(Long.valueOf(channelId));
            if (searchConfig == null) {
                return Constants.getResponse(Constants.CODE_ERROR, null, "读取数据发生异常").toJsonString();
            } else {
                return Constants.getResponse(Constants.CODE_SUC, searchConfig, "操作成功").toJsonString();
            }
        } catch (Exception e) {
            logger.error("[getPlatSettings][error]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    // 保存搜索限制
    public String savePlatSettings(String channelId, String configData) {
        try {
            if (!RegUtil.isPositiveInteger(channelId)) {
                return ServiceUtil.getResponseError("频道格式异常");
            }
            TSearchConfig entity = JSONObject.parseObject(configData, TSearchConfig.class);
            ChannelWebService.Iface service = getChannelService();
            entity.setId(Long.valueOf(channelId));
            entity.setOpUser(ServiceUtil.getOpUser());
            boolean result = service.saveSearchConfig(entity);
            if (result) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "操作成功");
            } else {
                return ServiceUtil.getResponseError(ERROR_EXIST);
            }
        } catch (Exception e) {
            logger.error("[savePlatSettings][error]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    @SkipAuthCheck
    public String pcaChannelFind(String categoryId, String channelId, String channelName, Integer pageNo, Integer pageSize) {
        if (StringUtils.isBlank(categoryId)) {
            return  ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
        pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
        pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;
        TPage page = new TPage(-1, pageNo, pageSize, "", "", true);

        try{
            ChannelWebService.Iface service =getChannelService();
            TChannelPcaPage tChannelPcaPage = service.findChannel(categoryId, channelId, channelName, page);
            if (tChannelPcaPage != null) {
                return Constants.getResponse(Constants.CODE_SUC, tChannelPcaPage, "操作成功").toJsonString();
            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
        }catch (Exception e){
            logger.error("[pcaChannelFind]", e);
            return  ServiceUtil.getResponseError(PARAMETER_ERROR);
        }

    }



    private boolean validChannelListParams(String liveType, String type,
                                           String qipuId, String name,
                                           String startDate, String endDate,
                                           String isEnable, String isDelete,
                                           Map<String, String> params) {
        if (StringUtils.isNotBlank(name)) {
            params.put("name", name);
        }
        if (StringUtils.isNotBlank(liveType)) {
            if (RegUtil.isNonnegativeInteger(liveType)) {
                params.put("liveType", liveType);
            } else {
                return false;
            }
        }
        if (StringUtils.isNotBlank(type)) {
            if (RegUtil.isNonnegativeInteger(type)) {
                params.put("type", type);
            } else {
                return false;
            }
        }
        if (StringUtils.isNotBlank(qipuId)) {
            if (RegUtil.checkChannelQipuId(qipuId)) {
                params.put("qipuId", qipuId);
            } else {
                return false;
            }
        }

        if (StringUtils.isNotBlank(startDate)) {
            if (RegUtil.isDateFormat(startDate)) {
                params.put("startDate", startDate);
            } else {
                return false;
            }
        }
        if (StringUtils.isNotBlank(endDate)) {
            if (RegUtil.isDateFormat(endDate)) {
                params.put("endDate", endDate);
            } else {
                return false;
            }
        }
        if (StringUtils.isNotBlank(isEnable)) {
            if (RegUtil.isInteger(isEnable)) {
                params.put("isEnable", isEnable);
            } else {
                return false;
            }
        }
        if (StringUtils.isNotBlank(isDelete)) {
            if (RegUtil.isNonnegativeInteger(isDelete)) {
                params.put("isDelete", isDelete);
            } else {
                return false;
            }
        }
        return true;
    }

    @SkipInterfaceLog
    public String getConfigs(String type) {
        if (StringUtils.isEmpty(type)) {
            return getResponseWithJsonp(Constants.CODE_ERROR_PARAM, null, PARAMETER_ERROR);
        }
        try {
            ChannelWebService.Iface service = ServiceUtil.getChannelService();
            List<Map<String, String>> result = service.getConfig(type);
            if (result != null) {
                return getResponseWithJsonp(Constants.CODE_SUC, result, null);
            } else {
                return getResponseWithJsonp(Constants.CODE_FAIL, null, "获取失败");
            }
        } catch (Exception e) {
            logger.error("[configs]", e);
            return getResponseWithJsonp(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
    }

    @SkipInterfaceLog
    public String suggestChannelInfo(String channelQipuId, String channelName, String liveType) {
        if (StringUtils.isNotEmpty(channelQipuId) && StringUtils.isNumeric(channelQipuId) == false) {
            return Constants.getJsonResponse(Constants.CODE_ERROR_PARAM, null, PARAMETER_ERROR);
        }
        if (StringUtils.isNotEmpty(liveType) && StringUtils.isNumeric(liveType) == false) {
            return  Constants.getJsonResponse(Constants.CODE_ERROR_PARAM, null, PARAMETER_ERROR);
        }
        if (StringUtils.isEmpty(channelQipuId)) {
            channelQipuId = "0";
        }
        if (StringUtils.isEmpty(liveType)) {
            liveType = "0";
        }
        try{  ChannelWebService.Iface channelService = ServiceUtil.getChannelService();
            List<TChannel> result = channelService.suggestChannelInfo(Long.parseLong(channelQipuId), channelName, Integer.parseInt(liveType));

            List data = new ArrayList();
            for (TChannel item : result) {
                Map<String, String> _tmp = new HashMap<>();
                _tmp.put("channelQipuId", item.getQipuId() + "");
                _tmp.put("channelName", item.getName() + "");
                _tmp.put("liveType", item.getLiveType() + "");
                _tmp.put("pageUrl", item.getPageUrl() + "");
                _tmp.put("defaultLogUrl", item.getDefaultLogoUrl() == null ? "" : item.getDefaultLogoUrl() + "");
                data.add(_tmp);
            }
            return Constants.getJsonResponse(Constants.CODE_SUC, data, "获取成功");
        } catch (Exception e) {
            logger.error("[suggestChannelInfo]", e);
            return Constants.getJsonResponse(Constants.CODE_ERROR, null, ERROR_EXIST);
        }
    }
}
